package com.hzit.proxy.base;

import com.alibaba.fastjson.JSONObject;
import com.hzit.net.util.RedisUtil;
import com.hzit.net.util.WXNetUtil;

public class AccessToken {

    private static final String appid="wx9beafe92c6981906";
    private static final String appsecret="cf38f0d1419bd67df740020964c875f8";
    public static String getToken(){
        String key="weixin:token";
        String token = RedisUtil.get(key);
        if(token!=null){
            return token;
        }
        String remoteToken = remote();
        if(remoteToken!=null){
            RedisUtil.set(key,remoteToken,7000);
            return remoteToken;
        }
        return null;
    }

    private static String remote(){
        System.out.println("----->远程访问token");
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret;
        String result = WXNetUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.containsKey("access_token")){
            String token = jsonObject.getString("access_token");
            return token;
        }
        System.err.println("error:"+result);
        return null;
    }


//    public static void main(String[] args) {
//        String token = getToken();
//        System.out.println(token);
//    }
}
